using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hit : MonoBehaviour {

    Entity m_owner;
    List<Entity> m_entities;
    AudioSource m_audio;

    [SerializeField]
    AudioClip hit1;

    [SerializeField]
    AudioClip hit2;

    int indexHit = 0;

    public Entity Owner {  set { m_owner = value; } }

    private void Start()
    {
        m_entities = new List<Entity>();
        m_audio = GetComponent<AudioSource>();
    }

    public void Active()
    {
        if (m_entities.Count == 0)
            return;

        List<Entity> toRemove = new List<Entity>();

        foreach(Entity e in m_entities)
        {
            if(e == null)
            {
                toRemove.Add(e);
                continue;
            }

            
            if(m_audio != null)
            {
                m_audio.clip = indexHit == 0 ? hit1 : hit1;
                m_audio.Play();
                indexHit = indexHit == 0 ? 1 : 0;

            }
            e.takeDamages(m_owner.Strength);
        }

        foreach (Entity tr in toRemove)
                m_entities.Remove(tr);

    }


    private void OnTriggerEnter(Collider other)
    {
        if (!other.GetComponent<Entity>())
            return;

        Entity e = other.GetComponent<Entity>();

        if (e != m_owner && e.Team != m_owner.Team)
            m_entities.Add(e);

    }

    private void OnTriggerExit(Collider other)
    {
        if (!other.GetComponent<Entity>())
            return;

        Entity e = other.GetComponent<Entity>();

        if (m_entities.Contains(e))
            m_entities.Remove(e);
    }
}
